package common.action;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sf.json.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import common.utils.FileUtil;


@Controller("ueditorupload")
@Scope("prototype")
public class UeditorUploadAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	
	private String UPLOADFILE="uploadfile";
	
	private File file;
	private String filename;
	private String descfield;//无值则和filename一样(只真对图片)

	public void image() throws Exception {
		List<String> fileTypes = new ArrayList<String>();
		String type ="*.jpg;*.png;*.jpeg;*.bmp;*.gif;";
		double size=2;
		String[] types = type.split(";");
		for (int i = 0; i < types.length; i++) {
			fileTypes.add(types[i].replace("*.",""));
		}
		response.getWriter().write(upload(fileTypes,size));
	}

	private String upload(List<String> fileTypes,double maxSize)
	{

		String fileExt = filename.substring(filename.lastIndexOf(".") + 1)
				.toLowerCase();
		if(null!=fileTypes)
		{
			if (!fileTypes.contains(fileExt)) {
				return	getError("上传文件扩展名["+fileExt+"]是不允许的扩展名。");
			}
		}
		if (filename.length() > maxSize*1024*1024) {
			return 	getError("上传文太大");
        }
		// 创建文件夹
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String ymd = sdf.format(new Date());
		String savePath=UPLOADFILE+"/"+ ymd + "/";
		String newfilename = FileUtil.randomRename(filename);
		File dirFile = new File(rootPath+savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		
			file.renameTo(new File(rootPath+savePath + newfilename));
		return "{'state':'SUCCESS','url':'"+savePath+newfilename
		+ "','alt':'" + descfield + "','original':'"
		+filename + "','type':'"+fileExt+"'}";
	}
	
	
	

	private String getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj.toString();
	}
	public void setFile(File file) {
		this.file = file;
	}
	public void setFilename(String filename) {
		this.filename = filename;
	}
	public void setDescfield(String descfield) {
		this.descfield = descfield;
	}
	
}